require 'extract/rules/rule'

module Extract
  
  class XMLRule < Extract::Rule
    
    def extract source_receiver, dest_receiver
      matchs = REXML::XPath.match source_receiver, xpath
      raise ArgumentError.new "matchs.length must be 0 or 1 instead of #{matchs.length}" if matchs.length > 1
      if matchs.length == 1 then
        val = matchs[0].text if matchs[0].instance_of? REXML::Element
        val = matchs[0].value if matchs[0].instance_of? REXML::Attribute
        val = matchs[0].string if matchs[0].instance_of? REXML::Comment
        preproces_val val
        handle_val val, dest_receiver
      end
    end
    
    def xpath
      raise NotImplementedError.new "Subclass must implents this method!!"
    end
    
    protected
    
    def preproces_val(val)
      val.downcase! unless val.nil?
    end
    
    def handle_val(val, dest_receiver)
      raise NotImplementedError.new "Subclass must implents this method!!"
    end
    
  end
  
end